
#include <stdio.h>
#include <stdlib.h>

#define TEST 1

#define DEBUG(tag,fmt...)\
do {\
	if(tag) {\
		printf("%s [%d]: ", __FILE__, __LINE__);\
		printf(fmt);\
	}\
}while(0)

int test3(int test_count, int for_count){

#define TEST_COUNT	test_count
#define FOR_COUNT	for_count
#define RAND_SIZE 	rand()%10240+1
#define RAND_INDEX	rand()%TEST_COUNT
#define RAND_NUM	(rand()%TEST_COUNT)/2
#define RAND_STEP	rand()%4
#define S_RAND_SEED	0xFEFEFEFE

	int i,j,n,index,num,step;
	int msize;
	DEBUG(TEST,"%s\n", __func__);
	void **memblocks = calloc(test_count, sizeof(void*));
	struct timeval t_start1, t_start2, t_end, t_tmp;
	long cost_time1, cost_time2;

	srand((unsigned int)S_RAND_SEED);

	//get time
	gettimeofday(&t_start2, NULL);

	for(i=0;i<TEST_COUNT;i++){
		memblocks[i] = malloc(RAND_SIZE);
	}

	for(j = 0;j < FOR_COUNT;j ++)
	{
		index = RAND_INDEX;
		num = RAND_NUM;
		step = RAND_STEP;
		i = 0;
		n = index;
		while(i < num)
		{
			if(n >= TEST_COUNT)
			{
				n = 0;
			}
			free(memblocks[n]);
			memblocks[n] = malloc(RAND_SIZE);
			i ++;
			n += step;
		}
	}

	for(i=0;i<TEST_COUNT;i++){
		free(memblocks[i]);
	}

	//get time
	gettimeofday(&t_end, NULL);

	//calculate time slot
	cost_time1 = t_start2.tv_usec - t_start1.tv_usec;
	cost_time2 = t_end.tv_usec - t_start2.tv_usec;
	//DEBUG(TEST,"Cost time1: %ld us\n", cost_time1);
	//DEBUG(TEST,"Cost time2: %ld us\n", cost_time2);

	//DEBUG(TEST,"Cost time1: %s s\n", diff_time(t_start1, t_start2));
	DEBUG(TEST,"Cost time2: %s s\n", diff_time(t_start2, t_end));

	return 0;
}
